const ComponentLogin = {
  template: `
        <div class="login-page">
            <div class="login-container">
                <h2>用户{{ isRegister ? '注册' : '登录' }}</h2>
                <form @submit.prevent="handleLogin">
                    <div class="form-item">
                        <span class="icon user_icon"></span>
                        <input 
                            type="text" 
                            v-model="username" 
                            placeholder="请输入账号"
                            required
                        >
                    </div>
                    <div class="form-item">
                        <span class="icon password_icon"></span>
                        <input 
                            type="password" 
                            v-model="password" 
                            placeholder="请输入密码"
                            required
                            @keyup.enter="handleLogin"
                        >
                    </div>
                    <div class="form-item" v-if="isRegister">
                        <span class="icon password_icon"></span>
                        <input 
                            type="password" 
                            v-model="repeatPassword" 
                            placeholder="请再次输入密码"
                            required
                            @keyup.enter="handleLogin"
                        >
                    </div>
                    <div class="form-item _btn" @click="handleLogin">{{ isRegister ? '注册并登录' : '登 录'}}</div>
                    <div v-if="errorMsg" class="error-message">
                        {{ errorMsg }}
                    </div>
                </form>
                <div class="handleRegister" @click="handleRegisters">{{ isRegister ? '已有账号, 去登录' : '注册账号'}}</div>
            </div>
        </div>
    `,
  data() {
    return {
      username: '',
      password: '',
      repeatPassword: '',
      errorMsg: '',
      isRegister: false
    }
  },
  methods: {
    // 简单的混淆函数
    encodeToken(str) {
      // 基础的 Base64 编码
      let base64 = btoa(str);
      // 简单的字符替换
      return base64
        .split('').reverse().join('')  // 反转字符串
        .replace(/=/g, '$')           // 替换等号
        .replace(/\+/g, '_')          // 替换加号
        .replace(/\//g, '-');         // 替换斜杠
    },
    async handleLogin() {
      const _this = this;
      if (this.isRegister) {
        if (!/^[A-Za-z0-9]{5,}$/.test(this.username )) {
          layer.msg('用户名必须是5位数字或大小写字母');
          return false;
        }
        if (!/^[A-Za-z0-9]{5,}$/.test(this.password )) {
          layer.msg('密码必须是5位数字或大小写字母');
          return false;
        }
        if (this.password  !== this.repeatPassword) {
          layer.msg('两次输入的密码不一致');
          return false;
        }

        $.ajax({
          type: "POST",
          url: '/ietm/user/add',
          data: {
            "userName": _this.username,
            "password": _this.password,
          },
          dataType: "JSON",
          success: function (res) {
            if (res.code == 200) {
              layer.msg('注册成功 !');
              _this.isRegister = false;
              _this.handleLogin();
            } else {
              if (res.msg.includes('失败')) {
                layer.msg(res.msg);
              } else {
                layer.msg('注册失败 !');
              }
            }
          }, error: function (res) {
            if (res.msg.includes('失败')) {
              layer.msg(res.msg);
            } else {
              layer.msg('注册失败 !');
            }
          }
        })

      } else {
        try {
          this.errorMsg = '';
          this.password = this.password.trim();
          this.username = this.username.trim();
          // 基本验证
          if (!this.username || !this.password) {
            this.errorMsg = '请输入用户名和密码';
            return;
          }

          // 这里应该是实际的登录验证逻辑
          // 示例中我们模拟一个简单的验证
          if (this.username.length < 3 || this.password.length < 5) {
            this.errorMsg = '用户名或密码格式不正确';
            return;
          }
          
          $.ajax({
            type: "POST",
            url: '/ietm/login',
            data: {
              "username": this.username,
              "password": this.password,
            },
            // dataType: "JSON",
            success: function (res) {
              if (res.code == 200) {
                // layer.msg('登录成功 !');
                // 生成加密的 token
                const rawToken = `${_this.username}:${_this.password}:${Date.now()}`;
                const token = _this.encodeToken(rawToken);

                // 设置 cookie
                // _this.setLocalStorage('systemToken', token);
                sessionStorage.setItem('systemToken', token);
                // document.cookie = `Authorization=${res.data.token}`; // ; path=/;

                // 保存用户信息
                localStorage.setItem('username', _this.username);
                localStorage.setItem('userInfo', JSON.stringify({ username: _this.username }));

                // 登录成功后跳转
                _this.$router.push('/home');
              } else {
                if (res.msg.includes('失败')) {
                  layer.msg(res.msg);
                } else {
                  layer.msg('登录失败 !');
                }
              }
            }, error: function (err) {
              console.log(err, '3173021707111');
              if(err.status!==200){
                layer.msg('登录失败!');
              }else{
                layer.msg(err.responseJSON.msg);
              }
            }
          })

          return;


        } catch (error) {
          console.error('登录错误:', error);
          this.errorMsg = '登录失败，请重试';
        }
      }
    },
    async handleRegisters() {
      this.password = '';
      this.username = '';
      this.repeatPassword = '';
      this.isRegister = !this.isRegister;
      console.log('397217391');
    },
    // 注册
    async handleRegister() {
      let layer = layui.layer;
      let form = layui.form;
      var _this = this;
      const layerIndex = layer.open({
        type: 1,
        area: '350px',
        resize: false,
        shadeClose: true,
        title: '用户注册',
        content: `
          <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
            <div class="demo-login-container">
              <!-- 用户名输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="text" 
                    name="username" 
                    lay-verify="required|username" 
                    placeholder="用户名 (5位数字/字母)" 
                    lay-reqtext="请填写用户名" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="clear">
                </div>
              </div>
              <!-- 密码输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="password" 
                    name="password" 
                    lay-verify="required|password" 
                    placeholder="密码 (5位数字/字母)" 
                    lay-reqtext="请填写密码" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="eye">
                </div>
              </div>
              <!-- 确认密码输入框 -->
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <input 
                    type="password" 
                    name="confirm_password" 
                    lay-verify="required|confirmPwd" 
                    placeholder="确认密码" 
                    lay-reqtext="请确认密码" 
                    autocomplete="off" 
                    class="layui-input" 
                    lay-affix="eye">
                </div>
              </div>
              <!-- 提交按钮 -->
              <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">注册</button>
              </div>
            </div>
          </div>
        `,
        success: function () {
          // 对弹层中的表单进行初始化渲染
          form.render();

          // 自定义表单校验规则
          form.verify({
            username: function (value) {
              if (!/^[A-Za-z0-9]{5,}$/.test(value)) {
                layer.msg('用户名必须是5位数字或大小写字母');
                return true;
              }
            },
            password: function (value) {
              if (!/^[A-Za-z0-9]{5,}$/.test(value)) {
                layer.msg('密码必须是5位数字或大小写字母');
                return true;
              }
            },
            confirmPwd: function (value) {
              const password = document.querySelector('input[name="password"]').value;
              if (value !== password) {
                layer.msg('两次输入的密码不一致');
                return true;
              }
            }
          });

          // 表单提交事件
          form.on('submit(demo-login)', function (data) {
            const field = data.field; // 获取表单字段值
            // 显示填写结果，仅作演示用
            // layer.alert(JSON.stringify(field), {
            //   title: '当前填写的字段值'
            // });
            console.log(JSON.stringify(field), '2301730173');

            $.ajax({
              type: "POST",
              url: '/ietm/user/add',
              data: {
                "userName": field.username,
                "password": field.password,
              },
              dataType: "JSON",
              success: function (res) {
                if (res.code == 200) {
                  layer.msg('注册成功 !');
                  _this.username = field.username;
                  _this.password = field.password;
                  _this.handleLogin();
                } else {
                  if (res.msg.includes('失败')) {
                    layer.msg(res.msg);
                  } else {
                    layer.msg('注册失败 !');
                  }
                }
              }, error: function (res) {
                if (res.msg.includes('失败')) {
                  layer.msg(res.msg);
                } else {
                  layer.msg('注册失败 !');
                }
              }
            })
            // 此处可执行 Ajax 等操作
            // …
            return false; // 阻止默认 form 跳转
          });
        }
      });


    }
  }
};


// 添加一些基本样式
const style = document.createElement('style');
style.textContent = `
    .login-page {
        width: 100%;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background: url('./img/bg.png') no-repeat center center;
        background-size: 100% 100%;
       
    }
    .handleRegister{
        position: absolute;
        bottom: 10px;
        right: 43px;
        font-size: 12px;
        color: #ffffff;
        cursor: pointer;
    }
    .handleRegister:hover{
        text-decoration: underline;
    }  
    .login-container {
        width: 614px;
        min-height: 500px;
        position: absolute;
        right: 180px;
        padding: 1px 90px 60px;
        box-sizing: border-box;
        background: rgba(255, 255, 255, 0.95);
        background: #226aa1 url("./img/login-box.png") center/100% 100% no-repeat;
    }
    
    .login-container h2 {
        text-align: center;
        color: #fff;
        margin-bottom: 60px;
        font-size: 32px;
        font-weight: bold;
    }
    
    .form-item {
        position: relative;
        margin-bottom: 20px;
    }

    ._btn.form-item {
        height: 70px;
        margin-top: 45px;
        background: url("./img/login-button.png") center/100% 100% no-repeat;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        color: #fff;
        cursor: pointer;
    }

    .form-item .icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        color: #999;
        font-size: 18px;
    }

    .form-item .user_icon{
      width: 32px;
      height: 32px;
      margin-left: 5px;
      background: url("./img/account.png") center/100% 100% no-repeat;
    }
    .form-item .password_icon{
      width: 32px;
      margin-left: 5px;
      height: 32px;
      background: url("./img/password.png") center/100% 100% no-repeat;
    }
    
    .form-item input {
        width: 100%;
        height: 66px;
        color: #fff;
        padding: 12px 15px 12px 62px;
        border: 1px solid #84c2ff;
        font-size: 22px;
        box-sizing: border-box;
        background: #00000000;
        transition: all 0.3s ease;
    }

    .form-item input::placeholder {
        color: #c1c1c1;
    }
    
    .form-item input:focus {
        border-color: #4a90e2;
        box-shadow: 0 0 5px rgba(74, 144, 226, 0.3);
        outline: none;
    }
    
    .form-item button {
        width: 100%;
        padding: 12px;
        background-color: #4a90e2;
        color: white;
        border: none;
        border-radius: 5px;
        font-size: 16px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
    
    .form-item button:hover {
        background-color: #357abd;
    }
    
    .error-message {
        color: #ff4d4f;
        font-size: 14px;
        text-align: center;
        margin-top: 10px;
    }
    input:-internal-autofill-previewed,
    input:-internal-autofill-selected {
      -webkit-text-fill-color: #fff !important;
      color: #fff !important;
      -webkit-text-fill-font-size: 24px !important;
      background-clip: content-box !important;
      font-size: 24px !important;
      background-color: transparent !important;
      transition: background-color 1000s ease-out 0.5s, color 1000s ease-out 0.5s !important;
      background-color: #fff !important;
    }
`;
document.head.appendChild(style);
